package com.deyuanyun.pic.pig.controller;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.deyuanyun.pic.common.util.*;
import com.deyuanyun.pic.pig.controller.vo.PigTaskVO;
import com.deyuanyun.pic.pig.controller.vo.FromPigVO;
import com.deyuanyun.pic.pig.controller.query.QueryListVO;
import com.deyuanyun.pic.pig.controller.vo.ToPigVO;
import com.deyuanyun.pic.pig.controller.vo.TrackPointVO;
import com.deyuanyun.pic.pipe.domain.CenterLine;
import com.deyuanyun.pic.pipe.service.PipeCenterLineService;
import com.deyuanyun.pic.settings.controller.pipe.vo.PipePositionDTO;
import com.deyuanyun.pic.settings.service.pipe.PipeLocationService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.deyuanyun.pic.common.dto.PageJsonBean;
import com.deyuanyun.pic.common.util.ajax.AjaxSupport;
import com.deyuanyun.pic.common.util.web.Asserts;
import com.deyuanyun.pic.pig.service.CleanPipeLineManagerService;

/**
 * 任务管理控制类
 *
 * @author tt
 */
@Controller
@RequestMapping("/pig/cleanPipeLineManager")
public class CleanPipeLineManagerController extends PiggingBaseController {

    private static final String path = UploadUtil.ROOTPATH + UploadUtil.OTHERRES;

    @Resource
    private CleanPipeLineManagerService cleanPipeLineManagerService;
    @Resource
    private PipeCenterLineService pipeCenterLineService;
    @Resource
    private PipeLocationService pipeLocationService;

    @ModelAttribute
    public void init(Model model) {
        model.addAttribute("cleanPipeLineManager", "active");
    }

    /**
     * 跳转到任务管理页面
     *
     * @return
     */
    @RequestMapping("/getCleanPipeLineManagerIndex.html")
    public ModelAndView goPiggingManagerPage() {

        return forword("/cleanPipe/task/taskManage");
    }

    /**
     * 加载任务列表数据
     */
    @RequestMapping("/getPigTaskManagerList.json")
    @ResponseBody
    public void getCleanPipeLineManagerIndex(QueryListVO taskVo) {
        PageJsonBean jsonBean = new PageJsonBean();
        List<PigTaskVO> list = cleanPipeLineManagerService.getCleanPipeLineManagerIndex(taskVo);
        jsonBean.setList(list);
        AjaxSupport.sendSuccessText("","yyyy-MM-dd",  jsonBean);
    }

    /**
     * 任务删除
     *
     * @param
     * @return
     */
    @RequestMapping("/deletePigTask.json")
    @ResponseBody
    public void deleteFun(String[] idStr) throws Exception {
        Asserts.assertTrue(idStr.length>0, "未成功选中需要删除的任务");
        int i=cleanPipeLineManagerService.deleteTaskById(idStr);
        if(i>0){
            AjaxSupport.sendSuccessText("已选择"+idStr.length+"条清管任务，成功删除"+i+"条","");
        }else if(i==0){
            AjaxSupport.sendFailText("已发布的任务不能删除","");
        }

    }

    /**
     * 任务发布
     *
     * @param
     * @return
     */
    @RequestMapping("/publishPigTask.json")
    @ResponseBody
    public void publishPigTaskById(String[] idStr) throws Exception {
        Asserts.assertTrue(idStr.length > 0, "未成功选中需要发布的任务");
        int i =  cleanPipeLineManagerService.publishPigTaskById(idStr);
        if(i>0){
            AjaxSupport.sendSuccessText("已选择"+idStr.length+"条清管任务，成功发布"+i+"条","");
        }else if(i==0){
            AjaxSupport.sendFailText("已发布的任务不能再次发布","");
        }

    }

    /**
     * 根据任务Id或起止位置（场站阀室）ID和对应的绝对距离获取对应的mark点和收发球信息
     *
     * @param
     * @return
     */
    @RequestMapping("/queryPigAndPoint.json")
    @ResponseBody
    public void queryPigAndPoint(QueryListVO taskVo){
        Asserts.assertTrue(StringUtils.isNotNullEmpty(taskVo.getLineId()),"未选中管道！");
//        Asserts.assertTrue(null != taskVo.getBeginMile(),"未选中起点位置！");
//        Asserts.assertTrue(null != taskVo.getEndMile(),"未选中终点位置！");
        Map<String, Object> map = new HashMap<String, Object>();
        map = cleanPipeLineManagerService.queryPigAndPoint(map,taskVo);

        AjaxSupport.sendSuccessText("", map);
    }

    /**
     * 保存检测任务
     *
     * @param taskVo
     * @return
     * @throws ParseException
     */
    @RequestMapping("/saveTask.json")
    @ResponseBody
    public void saveTask(PigTaskVO taskVo, String[] points,String attId
                        /* @RequestParam("file") MultipartFile[] file*/) throws Exception {
        Asserts.assertTrue(StringUtils.isNotNullEmpty(taskVo.getTaskName()), "请填写任务名称");
        Asserts.assertTrue(StringUtils.isNotNullEmpty(taskVo.getPipeLineId()), "请选择管道");
        Asserts.assertTrue(StringUtils.isNotNullEmpty(taskVo.getFromPipeValveroomId()), "请选择起始位置");
        Asserts.assertTrue(StringUtils.isNotNullEmpty(taskVo.getToPipeValveroomId()), "请选择终点位置");
        Asserts.assertTrue(points != null && points.length>0, "请勾选跟踪点");
        Asserts.assertTrue(StringUtils.isNotNullEmpty(taskVo.getFromPigId()), "没有发球桶，请重新选择起点位置");
        Asserts.assertTrue(StringUtils.isNotNullEmpty(taskVo.getToPigId()), "没有收球桶，请重新选择终点位置");
        Asserts.assertTrue(StringUtils.isNotNullEmpty(taskVo.getPagType()), "请选择清管类型");
        Asserts.assertTrue(StringUtils.isNotNullEmpty(taskVo.getPagTool()), "请选择或填写清管工具");
        Asserts.assertTrue(DateUtil.isNotNull(taskVo.getPlanPagDateTime()), "请填写计划清管时间");


        int msgCode = cleanPipeLineManagerService.saveTask(taskVo,points,attId);
       /* String tid = "";
        if (map != null && ObjectUtil.isNotNullEmpty(map.get("taskId"))) {
            tid = map.get("tid").toString();
        }
        if (!StringUtils.isEmpty(tid)) {
            for (int i = 0; i < file.length; i++) {
                if (!file[i].isEmpty()) {
                    // 取得当前上传文件的文件名称
                    String sourceName = file[i].getOriginalFilename();
                    String fileType = sourceName.substring(sourceName.lastIndexOf("."), sourceName.length());
                    // 重命名文件
                    String targetName = UUID.randomUUID().toString().replace("-", "") + fileType;
                    // 定义上传路径
                    File localFile = new File(path, targetName);
                    if (!localFile.exists()) {
                        localFile.mkdirs();
                    }
                    file[i].transferTo(localFile);
                    cleanPipeLineManagerService.savefile(sourceName, UploadUtil.OTHERRES + targetName, tid);
                }
            }
        }*/
        if(msgCode == -1){
            AjaxSupport.sendFailText("任务名称重复",msgCode);
        }else if(msgCode == 0){
            AjaxSupport.sendFailText("保存任务失败",msgCode);
        }else if(msgCode > 0){
            AjaxSupport.sendSuccessText("成功保存任务"+msgCode+"条", msgCode);
        }
    }

    /**
     * 新增或修改任务进入页面
     *
     * @param taskId
     * @return
     */
    @RequestMapping("/addOrModify.html")
    public ModelAndView addOrModify(String taskId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("taskId",taskId);
        if (StringUtils.isNullEmpty(taskId)) {
            map.put("title", "新建任务");
        } else {
            map.put("title", "修改任务");
        }
        return forword("/cleanPipe/task/newBuildTask",map);
    }

    /**
     * 获取清管工具
     *
     * @param pagTypeName
     * @return
     */
    @RequestMapping("/getCleanTool.json")
    @ResponseBody
    public void getCleanTool(String pagTypeName) {
        Map<String, Object> map = new HashMap<String, Object>();

        if (null != pagTypeName && !"".equals(pagTypeName)) {
            map = cleanPipeLineManagerService.queryCleanTool(pagTypeName);
        }
        AjaxSupport.sendSuccessText("", map);
    }

    /**
     * 修改时获取任务信息（包括附件）
     *
     * @param taskId
     * @return
     */
    @RequestMapping("/modifyTask.json")
    @ResponseBody
    public void getTask(String taskId) {
        Asserts.assertTrue(!StringUtils.isEmpty(taskId), "获取任务数据异常，请刷新页面重试");
        Map<String,Object> map =new HashMap<String,Object>();
        map = cleanPipeLineManagerService.modifyTask(map,taskId);
        AjaxSupport.sendSuccessText("","yyyy-MM-dd", map);
    }

    /**
     * 获取复制任务弹窗数据
     *
     * @param taskId
     * @return
     * @throws Exception
     */
    @RequestMapping("/copyTask.json")
    @ResponseBody
    public void copyTask(String taskId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        if (!StringUtils.isEmpty(taskId)) {
            map = cleanPipeLineManagerService.copyTask(taskId);
        }
        AjaxSupport.sendSuccessText("","yyyy-MM-dd",  map);
    }

    /**
     * 保存复制的任务
     *
     * @param
     * @param
     * @param
     * @param
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping("/copySave.json")
    @ResponseBody
    public void copySave(PigTaskVO taskVo)
            throws Exception {
        Asserts.assertTrue(!StringUtils.isEmpty(taskVo.getId()), "数据异常，请刷新页面后重试");
        Asserts.assertTrue(!StringUtils.isEmpty(taskVo.getTaskName()), "任务名称不能为空");
        Asserts.assertTrue(!StringUtils.isEmpty(taskVo.getPagTool()), "清管工具不能为空");
        Asserts.assertTrue(DateUtil.isNotNull(taskVo.getPlanPagDateTime()), "计划时间不能为空");

        Map<String, Object> map = new HashMap<String, Object>();
        map = cleanPipeLineManagerService.copySave(taskVo);
        AjaxSupport.sendSuccessText("", map);
    }

    /**
     * 下载任务附件
     *
     * @param taskId

    @RequestMapping("/downloadTaskFile.json")
    @ResponseBody
    public void downloadTaskFile(HttpServletResponse response, String taskId) throws Exception {
        Asserts.assertTrue(!StringUtils.isEmpty(taskId), "数据异常，请稍后重试");
        // 相关附件
        List<Attachment> attaList = cleanPipeLineManagerService.selectAttachmentByTaskId(taskId);
        // 任务名称
        PigTaskVO task = cleanPipeLineManagerService.getTask(taskId);
        // 磁盘文件名
        String diskName = "";
        // 下载的文件名
        String downName = "";
        byte[] buffer = new byte[1024];
        if (attaList.size() > 1) { // 如果不止一条附件。则打包下载
            if (ObjectUtil.isNotNullEmpty(task)) {
                downName = task.getTaskName();
            }
            // 所有附件
            List<File> files = new ArrayList<File>();
            downName = downName + "的所有附件.rar";
            diskName = path + downName;
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(diskName));
            for (Attachment att : attaList) {
                if (ObjectUtil.isNotNullEmpty(att)) {
                    if (ObjectUtil.isNotNullEmpty(att.getId())) {
                        files.add(new File(UploadUtil.ROOTPATH + att.getPath()));
                    }
                }
            }
            for (int i = 0; i < files.size(); i++) {
                FileInputStream fis = new FileInputStream(files.get(i));
                out.putNextEntry(new ZipEntry(files.get(i).getName()));
                // 设置压缩文件内的字符编码，不然会变成乱码
                // out.setEncoding("GBK");
                int len;
                // 读入需要下载的文件的内容，打包到zip文件
                while ((len = fis.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                out.closeEntry();
                fis.close();
            }
            out.close();
            downFile(response, diskName, downName);
        } else if (attaList.size() == 1) {
            diskName = attaList.get(0).getPath();
            downName = attaList.get(0).getRealName();
            downFile(response, diskName, downName);
        } else {
            response.setHeader("Content-Disposition", "");
            AjaxResponse.sendText(response,"false");
        }
    } */

    /**
     * 文件下载
     *
     * @param response
     * @param
     * @throws Exception

    @ResponseBody
    private void downFile(HttpServletResponse response, String diskName, String downName) throws Exception {
        String filePath = UploadUtil.ROOTPATH + diskName;
        File file = new File(filePath);
        if (file.exists()) {
            InputStream ins = new FileInputStream(filePath);
            BufferedInputStream bins = new BufferedInputStream(ins);// 放到缓冲流里面
            OutputStream outs = response.getOutputStream();// 获取文件输出IO流
            BufferedOutputStream bouts = new BufferedOutputStream(outs);
            response.setContentType("application/x-download; charset=utf-8");// 设置response内容的类型
            response.setCharacterEncoding("UTF-8");
            // response.setHeader("Content-disposition", "attachment;filename="
            // + URLEncoder.encode(downName, "UTF-8"));// 设置头部信息
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(downName.getBytes("gb2312"), "ISO8859-1"));

            int bytesRead = 0;
            byte[] buffer = new byte[2048];
            // 开始向网络传输文件流
            while ((bytesRead = bins.read(buffer, 0, 2048)) != -1) {
                bouts.write(buffer, 0, bytesRead);
            }
            bouts.flush();
            ins.close();
            bins.close();
            outs.close();
            bouts.close();
        }
    }*/

    /**
     * 提供给GIS的接口  用于地图显示
     *
     * @param
     * @param
     * @param
     */
    @RequestMapping("/findAllMapData.json")
    @ResponseBody
    public void findAllMapData(QueryListVO taskVo,String[] pointArry,String activePointGisId) {
        JSONArray gisArray = new JSONArray();

        //根据管道查出管道gisId
        CenterLine centerLine = null;
        centerLine = pipeCenterLineService.getCenterLineByLineId(taskVo.getLineId());
        JSONObject lineGis = new JSONObject();
        lineGis.put("typeName", "pipeLine");
        if (centerLine != null) {
            lineGis.put("gisId", centerLine.getGisId());
        } else {
            lineGis.put("gisId", null);
        }

        //收发球是否易位
        lineGis.put("direction", taskVo.getReverse());
        //根据起止位置查出收发球的gisId
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject fromPigGis = new JSONObject();
        JSONObject toPigGis = new JSONObject();
        JSONObject markGis = new JSONObject();

        //得到收发球信息
        map = cleanPipeLineManagerService.queryPig(map,taskVo);

        //发球筒
        fromPigGis.put("typeName", "fromPig");
        if(null != map.get("fromPig")){
            fromPigGis.put("gisId",((Map)map.get("fromPig")).get("GISID"));
        }else{
            fromPigGis.put("gisId",null);
        }

        //收球筒
        toPigGis.put("typeName", "toPig");
        if(null != map.get("toPig")){
            toPigGis.put("gisId",((Map)map.get("toPig")).get("GISID"));
        }else{
            toPigGis.put("gisId",null);
        }



        //得到mark点的gisId
        markGis.put("typeName", "mark");
        String[] markGisArr = new String[pointArry.length];

        int index=0;
        for (String pointId : pointArry) {
            //根据已选跟踪点的Id查询gisId
            TrackPointVO trackPoint = cleanPipeLineManagerService.queryTrackPointById(pointId);
            if( null != trackPoint ){
                markGisArr[index] = trackPoint.getGisId();
                index++;
            }
        }
        markGis.put("gisIdArray", markGisArr);

        gisArray.add(lineGis);
        gisArray.add(fromPigGis);
        gisArray.add(toPigGis);
        gisArray.add(markGis);

        if(StringUtils.isNotNullEmpty(activePointGisId)){
            JSONObject activePoint = new JSONObject();
            activePoint.put("typeName","loc");
            activePoint.put("gisId",activePointGisId);
            activePoint.put("typeElement","mark");
            gisArray.add(activePoint);
        }

        AjaxSupport.sendSuccessText("",gisArray);
//        ResponseUtil.printl(response, gisArray.toJSONString(), "json");

    }

    /**
     * 根据管道ID得到起点终点都有收发球筒的管段集合
     * @param pipeLineId
     */
    @RequestMapping("/querySegmentByLineId.json")
    @ResponseBody
    public void querySegmentByLineId(@RequestParam("pipeLineId") String pipeLineId
            ,@RequestParam(value="pipeSegmentName",required = false)String pipeSegmentName ){
        Asserts.assertTrue(StringUtils.isNotNullEmpty(pipeLineId),"管道未选中！");
        Map map = new HashMap();
        map.put("pipeLineId",pipeLineId);
        map.put("pipeSegmentName",pipeSegmentName);
        List<Map<String,Object>> list = cleanPipeLineManagerService.querySegmentByLineId(map);
        AjaxSupport.sendSuccessText("",list);
    }

    /**
     * 根据管段ID得到 有收发球筒的起止位置
     * @param
     */
    @RequestMapping("/querySegmentInfoById.json")
    @ResponseBody
    public void querySegmentInfoById(String pipeSegmentId, ModelMap model){
        Asserts.assertTrue(StringUtils.isNotNullEmpty(pipeSegmentId),"管段未选中！");
        PipePositionDTO pipePosition = pipeLocationService.queryPipeSegmentPosition(pipeSegmentId);
        if(pipePosition.getBeginBallMileage()!=null && pipePosition.getEndBallMileage()!=null){
            model.addAttribute("pipePosition",pipePosition);
        }else{
            model.addAttribute("pipePosition",null);
        }

        AjaxSupport.sendSuccessText("",model);
    }


    /**
     * 根据管道ID得到 有收发球筒的起止位置
     * @param pipeLineId
     */
    @RequestMapping("/queryLineInfoById.json")
    @ResponseBody
    public void queryLineInfoById(String pipeLineId, ModelMap model){
        Asserts.assertTrue(StringUtils.isNotNullEmpty(pipeLineId),"管道未选中！");
        PipePositionDTO pipePosition = pipeLocationService.queryPipeLinePosition(pipeLineId);
        if(pipePosition.getBeginBallMileage()!=null && pipePosition.getEndBallMileage()!=null){
            model.addAttribute("pipePosition",pipePosition);
        }else{
            model.addAttribute("pipePosition",null);
        }

        AjaxSupport.sendSuccessText("",model);
    }

}
